package com.hfmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfmall.common.SkuData;
import com.hfmall.common.SkuDto;
import com.hfmall.entity.*;
import com.hfmall.mapper.*;
import com.hfmall.service.IHfGoodsinfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liclo
 * @since 2021-08-12
 */
@Slf4j
@Service
public class HfGoodsinfoServiceImpl extends ServiceImpl<HfGoodsinfoMapper, HfGoodsinfo> implements IHfGoodsinfoService {
    public List<HfGoodsinfo> hfGoodsinfoList;
    @Resource
    private HfGoodsinfoMapper hfGoodsinfoMapper;
    @Resource
    private HfClassMapper hfClassMapper;
    @Resource
    private HfCategoryServiceImpl hfCategoryService;
    @Resource
    private HfGoodsinfoServiceImpl hfGoodsinfoService;
    @Resource
    private HfGoodsMapper hfGoodsMapper;
    private Integer con;//统计
    private int len;

    @Resource
    private HfValueMapper hfValueMapper;
    @Resource
    private HfGoodsValuesMapper hfGoodsValuesMapper;
    @Resource
    private HfPicturesMapper hfPicturesMapper;

    @Override
    // 分页查询goodsInfo
    public Page<HfGoodsinfo> getGoodsInfo(Integer current, Integer size) {
        if (current == null || current == 0) {
            current = 1;
        }
        if (size == null || size == 0) {
            size = 5;
        }
        // 分页，设置false不查询总数
        Page<HfGoodsinfo> p = new Page(current, size);
        p.setCurrent(current);
        p.setSize(size);

        return hfGoodsinfoMapper.getAll(p);
    }

    @Override //根据分类id查询 商品共性表
    public List<HfGoodsinfo> getHfGoodsinfoByPid(int pid) {
        return hfGoodsinfoMapper.getHfGoodsinfoByPid(pid);
    }

    @Override
    //首页查询热门商品,num给定list数量
    public Page<HfGoodsinfo> getHot(int num) {
        if (num == 0) {
            num = 6;
        }
        Page<HfGoodsinfo> p = new Page(1, num, false);
        return hfGoodsinfoMapper.getHot(p);
    }

    @Override
    //首页查询一级分类(女装1,男装2,包包3,童装4,鞋靴5)商品
    public Page<HfGoodsinfo> getListByCategory(Integer page, Integer num, Integer pid) {
        if (num == null || num == 0) {
            num = 8;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Page<HfGoodsinfo> p = new Page(page, num, false);
        return hfGoodsinfoMapper.getByCategory(p, pid);
    }

    /**
     * @param utilPageGoodsinfoVO@return 根据条件查询商品(规格值数组,分类类别)
     */
    @Override
    public UtilPageGoodsinfoVO<HfGoodsinfo> getHfGoodsinfoListByCategoryL3Id(UtilPageGoodsinfoVO utilPageGoodsinfoVO) {
        List<String> classValue = utilPageGoodsinfoVO.getClassValue();//选择的规格样式的值
        len = classValue.size();//规格个数
        Map<Integer, Integer> keyClassValueCon = new HashMap<>(); //存储规格名:出现次数
        con = 1;
        Map<String, List<HfClass>> allClassMap = new HashMap<>();//存储所有规格值对应的规格数组
        classValue.forEach(v -> {//遍历规格的值
            log.debug("k-v:{}", v + ":" + hfClassMapper.getClassByValue(v));
            allClassMap.put(v, hfClassMapper.getClassByValue(v));
            hfClassMapper.getClassByValue(v).forEach((c) -> {//规格值对应的规格-分类ID L1级-id
                keyClassValueCon.put(c.getCategoryId(), con);
            });
            con++;
        });
//        log.debug("所有值:{}",  keyClassValueCon.values());
        List<Integer> categoryLv1IdList = new ArrayList<>();//存储类别交集-id
        keyClassValueCon.keySet().forEach(k -> {//遍历所有key
            int vCon = keyClassValueCon.get(k);
            if (vCon == len) {//规格值数组查询规格数组的-交集
                categoryLv1IdList.add(k);
            }
            keyClassValueCon.get(k);
        });
        /*****************************/
//        List<HfCategory> allHfCategoryLv3=new ArrayList<>();//所有查询条件合并后的lv3 Category
        List<Integer> allHfCategoryLv3Id = new ArrayList<>();
        categoryLv1IdList.forEach(id -> {
            List<HfCategory> hfCategoryLv3 = hfCategoryService.getCategoryLv3Byid(id);
            ;//对应分类的所有三级分类
//            allHfCategoryLv3.addAll(hfCategoryLv3);
            hfCategoryLv3.forEach(lv3 -> {
                allHfCategoryLv3Id.add(lv3.getId());
            });

        });
//        log.debug("all_lv3....>>>>>>{}",allHfCategoryLv3)
//        log.debug("all_lv3_id....>>>>>>{}",allHfCategoryLv3Id);
        /*------分类查询-----------*/
        Integer conSize = hfGoodsinfoMapper.pageSelectGoodsinfoBylv3Id(allHfCategoryLv3Id, null, null, null, null).size();//查询所有元素个数
        utilPageGoodsinfoVO.setConSize(conSize);//存入总元素个数

        Integer page = 0;
        if (utilPageGoodsinfoVO.getPage() != null) {
            Integer webPage = utilPageGoodsinfoVO.getPage(); //传入页码
            webPage = webPage - 1;
            if (webPage > 0) {
                page = webPage;
            }
        }else {
            utilPageGoodsinfoVO.setPage(1);
        }
        Integer size = 10;
        if (utilPageGoodsinfoVO.getSize() != null) {
            size = utilPageGoodsinfoVO.getSize();//传入页码显示个数
            Integer lastSize = conSize % size; //获取最后的元素个数
            Integer allPage = 1;
            if ((conSize - lastSize) > 0) {
                allPage = (conSize - lastSize) / size + 1; //总页数
            }
            utilPageGoodsinfoVO.setAllPage(allPage);
        }
        BigDecimal priceMax = utilPageGoodsinfoVO.getPriceMax();
        BigDecimal priceMix = utilPageGoodsinfoVO.getPriceMix();
        List<HfGoodsinfo> lv3HfGoodsinfoList = hfGoodsinfoMapper.pageSelectGoodsinfoBylv3Id(allHfCategoryLv3Id, page, size, priceMax, priceMix);//商品的结果
        utilPageGoodsinfoVO.setDataVO(lv3HfGoodsinfoList);//返回商品信息
        return utilPageGoodsinfoVO;
    }

    @Override
    /**根据Lv3级分类查询其所对应商品*/
    public List<HfGoodsinfo> getAllGoodsinfoByByCategoryL3Id(List<HfCategory> hfCategoryLv3) {
        List<HfGoodsinfo> hfGoodsinfoListAll = new ArrayList<>(); //输出值
        for (HfCategory c : hfCategoryLv3) {
//            log.debug(">>>>?c>>>>>>{}",c);
            if (c != null) {
                hfGoodsinfoList = hfGoodsinfoMapper.getHfGoodsinfoByPid(c.getId());
                if (hfGoodsinfoList != null) {
                    hfGoodsinfoList.forEach(hfGoodsinfo -> {
                        //共性id查询对应商品
                        List<HfGoods> hfGoodsList = hfGoodsMapper.getHfGoodsByInfoId(hfGoodsinfo.getId());
                        if (hfGoodsList != null) {
                            hfGoodsinfo.setHfGoodsList(hfGoodsList);
                        }
                        hfGoodsinfoListAll.add(hfGoodsinfo);//主分类对应的所有分类与对应商品
                    });
                }
            }
        }
//        log.debug(">>>l3>>>>>>>{}",hfCategoryLv3);
//        log.debug(">>>>>>>>>>{}",hfGoodsinfoListAll);
        return hfGoodsinfoListAll;
    }

    /**
     * 根据字符串msg 查询goodsName(慎用)
     *
     * @param msg
     */
    @Override
    public UtilPageGoodsinfoVO<HfGoodsinfo> getGoodsinfoListByLike(String msg, Integer wbpage, Integer wbsize) {
        UtilPageGoodsinfoVO<HfGoodsinfo> pageGoodsinfoVO = new UtilPageGoodsinfoVO();
        List<HfGoodsinfo> hfGoodsinfoList = hfGoodsinfoMapper.getGoodsinfoListByLike(null, null, null);
        Integer conSize = hfGoodsinfoList.size();//查询所有元素个数
        pageGoodsinfoVO.setConSize(conSize);//存入总元素个数
        Integer page = 0;
        if (wbpage != null) {
            Integer webPage = wbpage; //传入页码
            webPage = webPage - 1;
            if (webPage > 0) {
                page = webPage;
            }
            pageGoodsinfoVO.setPage(wbpage);
        }else{
            pageGoodsinfoVO.setPage(1);
        }
        Integer size = 3;
        if (wbsize != null) {
            size = wbsize;//传入页码显示个数
            Integer lastSize = conSize % size; //获取最后的元素个数
            Integer allPage = 1;
            if ((conSize - lastSize) < 0) {
                allPage = 1;
            } else {
                allPage = (conSize - lastSize) / size + 1; //总页数
            }
            pageGoodsinfoVO.setAllPage(allPage);//存入总页数
        }


        if (msg == null || msg.trim() == "" || hfGoodsinfoMapper.getGoodsinfoListByLike(msg, page, size).size() == 0) {
            pageGoodsinfoVO.setDataVO(hfGoodsinfoMapper.getGoodsinfoListByLike(null, page, size));
            //所有
//            log.debug("pageGoodsinfoVO>>>>>>>:{}",pageGoodsinfoVO);
            return pageGoodsinfoVO;
        } else {
            pageGoodsinfoVO.setDataVO(hfGoodsinfoMapper.getGoodsinfoListByLike(msg, page, size));
//            log.debug("pageGoodsinfoVO>>msg>>>>>:{}",pageGoodsinfoVO);
            return pageGoodsinfoVO;
        }

    }


    /**
     * 根据类别分类查询
     */
    public UtilPageGoodsinfoVO<HfGoodsinfo> getPageGoodsinfoListByCategoryId(int id) {
        UtilPageGoodsinfoVO<HfGoodsinfo> utilPageGoodsinfoVO = new UtilPageGoodsinfoVO<>();

        List<Integer> allHfCategoryLv3Id = new ArrayList<>();
        hfCategoryService.getCategoryLv3Byid(id).forEach(lv3 -> { //所有lv3级id
            allHfCategoryLv3Id.add(lv3.getId());
        });

//        log.debug("all_lv3....>>>>>>{}",allHfCategoryLv3)
//        log.debug("all_lv3_id....>>>>>>{}",allHfCategoryLv3Id);
        /*------分类查询-----------*/
        Integer conSize = hfGoodsinfoMapper.pageSelectGoodsinfoBylv3Id(allHfCategoryLv3Id, null, null, null, null).size();//查询所有元素个数
        utilPageGoodsinfoVO.setConSize(conSize);//存入总元素个数

        Integer page = 0;
        if (utilPageGoodsinfoVO.getPage() != null) {
            Integer webPage = utilPageGoodsinfoVO.getPage(); //传入页码
            webPage = webPage - 1;
            if (webPage > 0) {
                page = webPage;
            }
        }else {
            utilPageGoodsinfoVO.setPage(1);//存入page
        }
        utilPageGoodsinfoVO.setPage(page);//存入page
        Integer size = 3;
        if (utilPageGoodsinfoVO.getSize() != null) {
            size = utilPageGoodsinfoVO.getSize();//传入页码显示个数

            Integer lastSize = conSize % size; //获取最后的元素个数
            Integer allPage = 1;
            if ((conSize - lastSize) < 0) {
                allPage = 1;
            } else {
                allPage = (conSize - lastSize) / size + 1; //总页数
            }
            utilPageGoodsinfoVO.setAllPage(allPage);//存入总页数
        }
        utilPageGoodsinfoVO.setSize(size);//存入size
        BigDecimal priceMax = utilPageGoodsinfoVO.getPriceMax();
        BigDecimal priceMix = utilPageGoodsinfoVO.getPriceMix();
        List<HfGoodsinfo> lv3HfGoodsinfoList = hfGoodsinfoMapper.pageSelectGoodsinfoBylv3Id(allHfCategoryLv3Id, page, size, priceMax, priceMix);//商品的结果
        utilPageGoodsinfoVO.setDataVO(lv3HfGoodsinfoList);//返回商品信息
        return utilPageGoodsinfoVO;
    }


    /**
     * 多条件分页查询
     *
     * @author liclo
     * @date 2021/8/20
     */
    @Override
    public Page<HfGoodsinfo> getByCondition(Integer current, Integer size, HfGoodsinfo goodsinfo) {
        if (current == null || current == 0) {
            current = 1;
        }
        if (size == null || size == 0) {
            size = 5;
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like(StringUtils.hasLength(goodsinfo.getGoodsName()), "goods_name", goodsinfo.getGoodsName())
                .eq(StringUtils.hasLength(goodsinfo.getGoodsNo()), "goods_no", goodsinfo.getGoodsNo())
                .ge(!StringUtils.isEmpty(goodsinfo.getMin()), "price", goodsinfo.getMin())
                .le(!StringUtils.isEmpty(goodsinfo.getMax()), "price", goodsinfo.getMax())
                .eq(StringUtils.hasLength(goodsinfo.getStatus()), "status", goodsinfo.getStatus())
                .eq(StringUtils.hasLength(goodsinfo.getHot()), "hot", goodsinfo.getHot());

        Page<HfGoodsinfo> p = new Page<>(current, size);
        return hfGoodsinfoMapper.selectPage(p, wrapper);
    }

    @Value("${gfhf.images}")
    private String imagePath;


    @Override
    @Transactional
    public void add(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        File f = new File(imagePath);
        if (!f.isDirectory()) {
            f.mkdir();
        }
        if (!isMultipart) {
            return;
        }
        // spu,商品信息
        HfGoodsinfo goodsinfo = new HfGoodsinfo();
        goodsinfo.setNo(Integer.valueOf(parameterMap.get("no")[0]));
        goodsinfo.setGoodsName(parameterMap.get("goodsName")[0]);
        goodsinfo.setHot(parameterMap.get("ishot")[0]);
        goodsinfo.setDescriptors(parameterMap.get("descriptors")[0]);
        goodsinfo.setWeight(parameterMap.get("weight")[0]);
        goodsinfo.setPid(Integer.valueOf(parameterMap.get("pid")[0]));
        goodsinfo.setStatus("y");
        goodsinfo.setGoodsNo(getGoodsNo());

        List<SkuDto> skuDtos = JSON.parseArray(parameterMap.get("skuStockList")[0], SkuDto.class);
        log.debug("skuDtos:{}", skuDtos);

        BigDecimal price = new BigDecimal(Integer.MAX_VALUE);

        for (int i = 0; i < skuDtos.size(); i++) {
            if (skuDtos.get(i).getPrice().compareTo(price) == -1) {
                price = skuDtos.get(i).getPrice();
            }
        }
        goodsinfo.setPrice(price);

        // 封面图
        MultipartFile coverPic = multipartRequest.getFile("coverPic");
        String newFileName = getNewFileName(coverPic.getOriginalFilename());
        try {
            coverPic.transferTo(new File(f + "\\" + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        goodsinfo.setCoverPath("/" + newFileName);

        // 添加goodsinfo
        hfGoodsinfoMapper.insert(goodsinfo);
        // 获得规格
        List<HfClass> hfClasses = getclassId(goodsinfo.getPid());
        // 规格值
        HashSet<String> val = new HashSet<>();
        for (int i = 0; i < skuDtos.size(); i++) {
            val.add(skuDtos.get(i).getSkuData().get(0).getValue());
        }
        // 获取图片
        HashMap<String, List> picMap = new HashMap<>();
        for (String v : val) {
            List<MultipartFile> pics = multipartRequest.getFiles(v);
            ArrayList<String> strings = new ArrayList<>();
            for (int i = 0; i < pics.size(); i++) {
                String path = getNewFileName(pics.get(i).getOriginalFilename());
                try {
                    pics.get(i).transferTo(new File(f + "\\" + path));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                strings.add("/" + path);
            }
            picMap.put(v, strings);
        }

        for (int i = 0; i < skuDtos.size(); i++) {
            // sku
            HfGoods hfGoods = new HfGoods();
            hfGoods.setGoodsinfoId(goodsinfo.getId());
            hfGoods.setSku(goodsinfo.getGoodsNo() + "-" + (i + 1));
            hfGoods.setPrice(skuDtos.get(i).getPrice());
            hfGoods.setStock(skuDtos.get(i).getStock());
            hfGoodsMapper.insert(hfGoods);

            // 规格值
            List<SkuData> skuDatas = skuDtos.get(i).getSkuData();
            for (int j = 0; j < skuDatas.size(); j++) {
                for (int m = 0; m < hfClasses.size(); m++) {
                    if (skuDatas.get(j).getKey().equals(hfClasses.get(m).getClassName())) {
                        String value = skuDatas.get(j).getValue();

                        HfValue hfValue = new HfValue();
                        hfValue.setValue(value);
                        hfValue.setClassId(hfClasses.get(m).getId());

                        hfValueMapper.insert(hfValue);

                        // 商品-规格值
                        HfGoodsValues hfGoodsValues = new HfGoodsValues();
                        hfGoodsValues.setValueId(hfValue.getId());
                        hfGoodsValues.setSkuId(hfGoods.getId());

                        hfGoodsValuesMapper.insert(hfGoodsValues);
                    }
                }
            }
            // 商品图


            List<String> list = picMap.get(skuDtos.get(i).getSkuData().get(0).getValue());
            list.forEach(l -> {
                HfPictures hfPictures = new HfPictures();
                hfPictures.setGoodsId(hfGoods.getId());
                hfPictures.setPath(l);
                hfPicturesMapper.insert(hfPictures);
            });
        }


    }

        /**
         * 新文件名
         *
         * @author liclo
         * @date 2021/8/20
         */
    private String getNewFileName(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        return newName;
    }

    private String getGoodsNo() {
        return "NO." + UUID.randomUUID().toString().replaceAll("-", "");
    }


        /**
         * 根据商品的第三级分类id查询class信息
         *
         * @return
         * @author liclo
         * @date 2021/8/20
         */
        private List<HfClass> getclassId (Integer id){
            Integer pid = hfCategoryService.getHfCategoryLv1(id).getId();

            QueryWrapper<HfClass> wrapper = new QueryWrapper<>();
            wrapper.eq("category_id", pid);

            return hfClassMapper.selectList(wrapper);
        }
    }

